package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.search.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
@Service
public class ApUserLoginServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserLoginService {
    @Override
    public ResponseResult login(LoginDto dto) {
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getEquipmentId()==null&&(StringUtils.isEmpty(dto.getPhone())||StringUtils.isEmpty(dto.getPassword()))){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"手机号和机器码至少有一个");
        }
        Map<String,Object>map = new HashMap<>();
        if (StringUtils.isNotBlank(dto.getPhone())&&StringUtils.isNotBlank(dto.getPassword())){
            ApUser apUser = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"该用户不存在");
            }
            String salt = apUser.getSalt();
            String password = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
            if (!password.equals(apUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            apUser.setPassword("");
            apUser.setSalt("");
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            map.put("user",apUser);
            map.put("token",token);
            return ResponseResult.okResult(map);
        }else {
            String token = AppJwtUtil.getToken(0L);
            map.put("token",token);
            return ResponseResult.okResult(map);

        }
    }
}
